<?php

namespace App\Services\User;

use App\CodeResponse;
use App\Models\User\Address;
use App\Services\BaseServices;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class AddressServices extends BaseServices
{
    public function getDefaultAddress($userId)
    {
        return Address::query()->where('user_id', $userId)
            ->where('is_default', 1)->first();
    }

    /**
     * 获取地址或者返回默认地址
     */
    public function getAddressOrDefault($userId, $addressId = null)
    {
        // 获取地址
        if (empty($addressId)) {
            $address = AddressServices::getInstance()->getDefaultAddress($userId);
        } else {
            $address = AddressServices::getInstance()->getAddress($userId, $addressId);
            if (empty($address)) {
                $this->throwBadArgumentValue();
            }
        }
        return $address;
    }

    /**
     * 获取地址列表
     * @param  int  $userId
     *
     * @return Address[]|Collection
     */
    public function getAddressListByUserId(int $userId)
    {
        return Address::query()->where('user_id', $userId)
            ->where('deleted', 0)->get();
    }

    /**
     * 获取用户地址
     * @param $userId
     * @param $addressId
     *
     * @return Address|Model|object|null
     */
    public function getAddress($userId, $addressId)
    {
        return Address::query()->where('user_id', $userId)->where('id', $addressId)
            ->where('deleted', 0)->first();
    }

    /**
     * 删除用户地址
     * @param $userId
     * @param $addressId
     *
     * @return bool|mixed|null
     */
    public function delete($userId, $addressId)
    {
        $address = $this->getAddress($userId, $addressId);
        if (is_null($address)) {
            $this->throwBusinessException(CodeResponse::PARAM_ILLEGAL);
        }
        return $address->delete();
    }
}
